class Result {
  constructor(res, code, data = null, message) {
    if (!res) throw new Error('Result未传入res对象');
    this.res = res;
    this.code = code;
    this.data = data;
    this.message = message;
  }

  codeToMessage(code) {
    if (this.message) return this.message;
    switch (code) {
      case 200:
        return '请求成功';
      case 401:
        return 'token无效';
      case 404:
        return '找不到资源';
      case 1200:
        return '未知错误';
      case 1201:
        return '邮箱已注册';
    }
  }

  success() {
    this.res.status(200).send({
      code: this.code,
      message: this.codeToMessage(this.code),
      data: this.data,
    });
  }

  fail(status = 200) {
    this.res.status(status).send({
      code: this.code || status,
      message: this.codeToMessage(this.code || status),
      data: this.data,
    });
  }
}

module.exports = Result;
